/* eslint-disable no-empty */
import { defineStore } from 'pinia'
import {
  getCookie,
  getQueryVariable,
  isEmptyObject,
  isWeChat,
  isAlipayClient
} from '@/utils/common'
import useConfigStore from './configStore'
import { powerBankApi, userApi, baseApi, moneyApi } from '@/api'
import useChatStore from './chatStore'
import wxShare from '@/common/wechat-share'

import { innovate_shopId } from '@/api/enum'
// @ts-ignore
declare var ap: any
const BASEURL = 'https://api.blacksilverscore.com'
// const BASEURL = 'http://192.168.169.222:8000'
export interface UserInfo {
  avatar: string
  id: number
  nickname: string
  phone: string
  rongToken: string
  gender: number
  inviteCode: string
  username: string
  user: object
  forwardFriendCircleReward: number
  forwardFriendReward: number
  forwardDouyinReward: number
}
const userStore = defineStore('user', {
  state: () => ({
    isAuthorize: false, // 是否授权
    isBindPhone: false, // 是否绑定手机
    userInfo: {} as UserInfo,
    accessToken: '',
    wxAccessToken: '',
    unionid: '',
    openid: '',
    wxUserInfo: {},
    walletList: [],
    hasNewDynamic: false,
    useShareCode: true,
    myShopList: [], // 用户拥有的店铺
    currentShop: {}, // 用户当前切换的店铺
    flqTicket: 0
  }),
  getters: {
    hasLogin: (state) => {
      return Boolean(state.accessToken) || getCookie('HYToken')
    },
    openIdgetter: (state) => {
      return state.openid || uni.getStorageSync('openid')
    },
    wxUserInfoGetter: (state) => {
      return state.wxUserInfo || uni.getStorageSync('wxUserInfo')
    },
    unionIdgetter: (state) => {
      return state.unionid || uni.getStorageSync('unionid')
    },
    accessTokenGetter: (state) => {
      return state.accessToken || uni.getStorageSync('accessToken')
    },
    userInfoGetter: (state) => {
      return state.userInfo || uni.getStorageSync('userInfo')
    }
  },
  actions: {
    syncSetMyShopList(list: any) {
      this.myShopList = list
      uni.setStorageSync('myShopList', list)
    },
    syncSetCurrentShop(shop: {}) {
      if (isEmptyObject(shop)) return
      this.currentShop = shop
      uni.setStorageSync('currentShop', shop)
    },
    syncSetUseShareCode(flag: boolean) {
      this.useShareCode = flag
    },
    syncSetOpenid(openid: string) {
      this.openid = openid
      uni.setStorageSync('openid', openid)
    },
    syncSetUnionid(unionid: string) {
      this.unionid = unionid
      uni.setStorageSync('unionid', unionid)
    },
    syncSetToken(token: string) {
      this.accessToken = token
      uni.setStorageSync('accessToken', token)
    },
    syncSetWxToken(token: string) {
      this.wxAccessToken = token
      uni.setStorageSync('wxAccessToken', token)
    },
    async syncSetUserInfo(data: object) {
      this.userInfo = data as UserInfo
      uni.setStorageSync('userInfo', data)
    },

    syncClearToken() {
      this.accessToken = ''
      uni.removeStorageSync('accessToken')
    },
    syncClearUserInfo() {
      this.userInfo = {} as UserInfo
      uni.removeStorageSync('userInfo')
    },
    syncSetWalletList(data: never[]) {
      if (data && data.length) {
        this.walletList = data
      }
    },

    // #region ***************** 复来券 *************************/
    async getMemberTotalFulaiquan() {
      const { data } = await moneyApi.getMemberTotalFulaiquan()
      console.log(data, '复来券')
      this.flqTicket = data
    },

    // #endregion

    getImgFullPath(suffix: string) {
      if (!suffix) return
      if (suffix.includes('http' || 'https')) {
        return suffix
      }
      const configStore = useConfigStore()
      return configStore.staticUrl + suffix
    },
    getUserInfo() {
      return new Promise((resolve, _reject) => {
        uni.request({
          url: `${BASEURL}/ups/api/v1/user/info`,
          method: 'GET',
          header: {
            Authorization: `Bearer ${this.accessToken}`
          },
          success: async (res) => {
            const { data } = res.data
            this.syncSetUserInfo(data)
            try {
              if (!!uni.getStorageSync('innovateType')) {
                // this.innovateBind()
              }
              // #ifdef H5
              //获取签名
              this.getWxSdkConfig()
              // #endif
              // // 登录融云IM
              // const chatStore = useChatStore()
              // chatStore.connect(this.userInfo?.rongToken)
            } catch (error) {
              console.log(error, 'getUserInfo')
            }
            resolve(data)
          }
        })
      })
    },
    loginByOpenId(openid?: any) {
      let type = 32
      // #ifdef H5
      type = 32
      // #endif
      // #ifdef MP-WEIXIN
      type = 33
      // #endif

      let that = this
      return new Promise((resolve, reject) => {
        const self = this // 保持 this 上下文
        const codeValue = openid || that.openIdgetter

        uni.request({
          url: `${BASEURL}/auth/api/v1/auth/login`,
          method: 'POST',
          header: {
            platform: type == 32 ? 50 : 33
            // // #ifdef H5
            // platform: 50,
            // // #endif
            // // #ifdef MP-WEIXIN
            // platform: 40,
            // // #endif
          },
          data: {
            type,
            code: codeValue,
            unionId: this.wxUserInfo?.unionid // 添加可选链防止 undefined 错误
          },
          success: (res) => {
            console.log('loginByOpenId===>', res, self.wxUserInfo)
            const { code, data } = res.data
            if (code === 200) {
              self.syncSetToken(data.accessToken)
              self.getUserInfo()
              resolve(true)
            } else {
              reject(new Error(`登录失败，错误码：${code}`))
            }
          },
          fail: (err) => {
            console.error('网络请求失败', err)
            reject(new Error('网络请求失败'))
          }
        })
      })
    },
    hlhyLoginByOpenId(openid?: any) {
      let type = 33
      console.log('isAlipayClient:', isAlipayClient())
      console.log('isWeChat:', isWeChat())

      if (isAlipayClient()) {
        type = 36
      } else if (isWeChat()) {
        type = 33
      } else {
        type = 32
      }

      console.log('type:', type, openid)

      let that = this
      return new Promise((resolve, reject) => {
        uni.request({
          url: `${BASEURL}/auth/api/v1/auth/login`,
          method: 'POST',
          header: {
            platform: type === 36 ? 62 : type === 33 ? 40 : 50
            // platform: 62
          },
          data: {
            type,
            code: openid || that.openIdgetter,
            unionId: this.unionIdgetter
          },
          success: (res) => {
            console.log(res, this.unionIdgetter, 'loginByOpenId')
            const { code, data } = res.data
            if (code === 200) {
              this.syncSetToken(data.accessToken)
              this.getUserInfo()

              resolve({ status: true, subscribe: 0 })
            } else {
              resolve({ status: false, subscribe: 0 })
            }
          }
        })
      })
    },
    wxWebLogin(code: any) {
      return new Promise((resolve, _reject) => {
        uni.request({
          url: `${BASEURL}/auth/api/v1/auth/wxWebLogin`,
          method: 'POST',
          header: {
            code,
            platform: 50
          },
          success: (res) => {
            const { data } = res.data
            console.log('公众号获取openid==>', data)
            if (data && data.access_token) {
              this.wxUserInfo = data
              this.syncSetWxToken(data.access_token)
              this.syncSetOpenid(data.openid)
              this.syncSetUnionid(data.unionid)
            }
            resolve(true)
          }
        })
      })
    },
    wxMiniLogin(code: any) {
      return new Promise((resolve, _reject) => {
        uni.request({
          url: `${BASEURL}/auth/api/v1/auth/wxMiniLogin`,
          method: 'POST',
          header: {
            code
          },
          success: (res) => {
            console.log(res, code, 'wxMiniLogin')
            const { data } = res.data
            this.wxUserInfo = data
            this.syncSetWxToken(data.access_token)
            this.syncSetOpenid(data.openid)
            this.syncSetUnionid(data.unionid)
            resolve(true)
          }
        })
      })
    },
    wxAuth(appId?: string): Promise<any> {
      return new Promise((resolve, _reject) => {
        const APPID = appId || 'wx0ffaafd066438895' //正式黑银生活appid
        // const APPID = appId || 'wx2db45f7e4d994732'
        // const APPID = appId || 'wxb1f182ce7a0b5f98'
        // const APPID = appId || 'wx2db45f7e4d994732'
        const SCOPE = 'snsapi_userinfo'
        const CODE = getQueryVariable('code')
        const REDIRECT_URL = encodeURIComponent(window.location.href)
        console.log(
          'REDIRECT_URL===>',
          REDIRECT_URL,
          CODE,
          window.location.href
        )
        if (!CODE) {
          console.log('跳转微信auth')
          const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APPID}&redirect_uri=${REDIRECT_URL}&response_type=code&scope=${SCOPE}&state=STATE#wechat_redirect`
          console.log('授权authUrl==>', authUrl)
        
          window.location.href = authUrl

          return
        }
        console.log('获取到微信code==>', CODE)
        resolve({ code: CODE })
      })
    },
    // 支付宝H5授权
    async aliAuth() {
      console.log('aliAuth')
      try {
        const res = await new Promise((resolve, reject) => {
          ap.getAuthCode(
            {
              appId: '2021004138686349',
              scopes: ['auth_base']
            },
            (res: any) => {
              if (res.error) {
                reject({ error: res.error, errorDesc: res.errorDesc })
              } else {
                resolve(res.authCode)
              }
            }
          )
        })
        alert(res)
        if (res) {
          uni.setStorageSync('code', res)
          await this.aliH5Login(res)
        }
      } catch (error: any) {
        uni.showToast({
          title: error.errorDesc || '授权失败，请重试',
          icon: 'none'
        })
      }
    },
    // 支付宝H5获取openId
    aliH5Login(code: any) {
      console.log('获取支付宝code')

      return new Promise((resolve, reject) => {
        uni.request({
          // url: `https://api.blacksilverscore.com/auth/api/v1/auth/login`,
          // url: `http://192.168.169.133:5173/auth/api/v1/auth/login`,
          url: `${BASEURL}/auth/api/v1/auth/aliH5Login`,
          method: 'POST',
          header: {
            platform: 62, // 鑫弗莱
            code
          },
          success: (res) => {
            const { data } = res.data
            console.log('alilogin===>', data)
            if (data && data.alipay_system_oauth_token_response) {
              const { open_id, user_id } =
                data.alipay_system_oauth_token_response
              this.syncSetOpenid(user_id)

              // 返回 user_id
              resolve(user_id)
            } else {
              // 如果数据格式不符合预期，返回错误
              reject(new Error('Failed to get user_id'))
            }
          },
          fail: (err) => {
            // 请求失败处理
            reject(err)
          }
        })
      })
    },
    // aliAuthHb() {
    //   console.log('aliAuth', )
    //   const _this = this
    //   // @ts-ignore
    //   ap.getAuthCode({
    //     appId: '2021004138686349',
    //     scopes: ['auth_base'],
    //   }, function (res: any) {
    //     const { authCode, error, errorDesc } = res
    //     if (error) {
    //       uni.showToast({
    //         title: errorDesc,
    //         icon: 'none'
    //       })
    //     }
    //     console.log(authCode,'支付宝的凑得！！！！');
    //     return authCode
    //     // if (authCode) {
    //     //   uni.setStorageSync('code', authCode)
    //     //   _this.aliH5Login(authCode)
    //     // }
    //   })
    // },

    checkLoginState(data?: { routeType: string; qrCode: any }) {
      if (!this.hasLogin) {
        const cookie = getCookie('HYToken')
        if (cookie) {
          this.syncSetToken(cookie)
          return true
        }
        if (data?.routeType === 'redirectTo' && data?.qrCode) {
          console.log('参数==》', data?.qrCode)

          uni.redirectTo({
            url: `/pages/login/index?groupCode=${data?.qrCode.groupCode}&gid=${data?.qrCode.gid}&cid=${data?.qrCode.cid}`
          })
        } else if (data?.routeType === 'redirectTo') {
          uni.redirectTo({
            url: '/pages/login/index'
          })
        } else {
          uni.navigateTo({
            url: '/pages/login/index'
          })
        }
        return false
      }
      return true
    },
    async innovateBind() {
      const shareCode = uni.getStorageSync('shareCode')
      const innovateType = uni.getStorageSync('innovateType')
      const res = await userApi.innovateBind({
        userId: this.userInfo.id,
        shareCode,
        innovateType: innovateType || 1,
        shopId: innovate_shopId[innovateType as keyof typeof innovate_shopId]
      })
      if (res.code === 200) {
        uni.showToast({
          title: res.data || '绑定成功',
          icon: 'none',
          duration: 3000
        })
        uni.redirectTo({
          url: '/pages/register/innovate-bind-success'
        })
      } else {
        uni.switchTab({
          url: '/pages/shortVideo/index'
        })
      }

      uni.removeStorageSync('innovateType')
    },
    async getWxSdkConfig() {
      const { origin, pathname, hash } = window.location
      const url = `${origin + pathname + hash}`
      console.log(url, '网址')

      const { data } = await baseApi.getWxSdkConfig(url)
      console.log('wxSdkConfig===>', data)
      wxShare.jsSdkConfig(data)
    }
  }
})

export default userStore
